<template>
  <section class="padding EndWaybillList">
    <el-card>
      <div slot="header" class="clearfix relative ">
        <span class="title-icon">亚马逊店铺管理</span>
        <div class="absolute add-btn-box">
          <el-button
            type="success"
            size="mini"
            icon="el-icon-plus"
            @click="addInfo"
          >
            新增
          </el-button>
        </div>
      </div>

      <el-row :gutter="10">
        <el-col
          v-for="(item, index) in pickupInfo"
          :key="index"
          :md="24"
          :lg="24"
        >
          <div class="my-profile-info-box flex justify-between">
            <div class="" style="width:90%">
              <el-row>
                <el-col :span="6">
                  <div class="margin-bottom-sm ">
                    <span>店铺ID：{{ item.sellingPartnerId }} </span>
                  </div>
                </el-col>

                <el-col :span="6">
                  <div class="margin-bottom-sm ">
                    店铺名称：{{ item.shopName }}
                  </div>
                </el-col>
                <el-col :span="6">
                  <div class="margin-bottom-sm ">
                    AccessToken：
                    <el-popover
                      placement="top-start"
                      width="400"
                      title="AccessToken："
                      trigger="hover"
                      :content="item.accessToken"
                    >
                      <span slot="reference" class="text-blue pointer">
                        展示
                      </span>
                    </el-popover>
                  </div>
                </el-col>

                <el-col :span="6">
                  <div class="margin-bottom-sm ">
                    RefreshToken：
                    <el-popover
                      placement="top-start"
                      title="RefreshToken："
                      width="400"
                      trigger="hover"
                      :content="item.refreshToken"
                    >
                      <span slot="reference" class="text-blue pointer">
                        展示
                      </span>
                    </el-popover>
                  </div>
                </el-col>
                <el-col :lg="24" class="padding-left">
                  <div
                    v-for="items in item.marketplaces"
                    :key="items.id"
                    class="margin-bottom-sm "
                  >
                    <el-row>
                      <el-col :span="6"> 站点ID： {{ items.id }} </el-col>
                      <el-col :span="6"> 站点名称：{{ items.name }} </el-col>
                      <el-col :span="6">
                        站点国家：{{ items.countryCode }}
                      </el-col>
                      <el-col :span="6">
                        默认货币：{{ items.defaultCurrencyCode }}
                      </el-col>
                    </el-row>
                  </div>
                </el-col>
              </el-row>
            </div>
            <div class="flex justify-between flex-direction">
              <div class="text-lg">
                <i
                  class="el-icon-edit-outline pointer margin-right text-blue"
                  title="编辑"
                  @click="editInfo(index)"
                />

                <i
                  class="el-icon-remove margin-right"
                  :class="{ 'text-red': item.disable }"
                  title="禁用"
                />
                <i
                  class="el-icon-s-check margin-right"
                  :class="{ 'text-green': !item.disable && item.refreshToken }"
                  title="授权"
                  @click="toCheck"
                />
                <i
                  class="el-icon-refresh margin-right text-blue pointer"
                  title="同步授权信息"
                  @click="synchronize(item)"
                />
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <el-dialog
      :title="editType === 'add' ? '新增店铺' : '编辑店铺'"
      width="36%"
      :visible.sync="dialogFormVisible"
      :before-close="handleClose"
    >
      <el-form
        ref="ruleForm"
        :rules="rules"
        label-position="left"
        label-width="100px"
        size="mini"
        :model="form"
        class="padding-lr-40"
      >
        <el-form-item prop="shopName">
          <div slot="label">店铺名称：</div>
          <el-input
            v-model.trim="form.shopName"
            placeholder="请填写店铺名称"
            clearable
          />
        </el-form-item>

        <el-form-item prop="sellingPartnerId">
          <div slot="label">店铺ID：</div>

          <el-input
            v-model.trim="form.sellingPartnerId"
            placeholder="请填写店铺ID"
            clearable
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm('ruleForm')">
          {{ editType === 'add' ? '立即创建' : '保存' }}
        </el-button>
        <el-button @click="resetForm('ruleForm')">重置</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
import { clone } from '@/utils/clone'

import { manualSync, saveOrUpdate, sotreList } from '@/api/myProfile'
export default {
  name: 'ShippingAddress',

  data() {
    return {
      editType: 'add',

      dialogFormVisible: false,
      form: {
        sellingPartnerId: '',
        shopName: ''
      },

      pickupInfo: [
        {
          id: 100,
          customerId: 4081,
          shopName: '九方通逊',
          sellingPartnerId: 'A1R2BKFEAVCSF',
          accessToken:
            'Atza|IwEBINraUjjO8yaDN_2vKLiwT3YCamUv2WcYWo8p6FQU9ZBn7G07xAzT0rNQbvcGWgggHiSGnpUjA7Gi95EC2gLz4R0g1LFerUJ5QFy-fXx6c_7S0nQ_gKPMhO8u0F2K2qRZBlLW6cAxi3PLR3scM89czgwFfqvfnYR-VbIlwqLv1vElnLVjI29LKtvVVEehapYByJHSeQVSVCDpAku899Ntxtcxs53RxdLALD-hYlPw7dco4104IW8JiCm_sMxvR0oMGlv_9tQLeIPfTyG2iapAsilwqPyaUhtKlCdxqilXLEY7ug',
          refreshToken:
            'Atzr|IwEBILSi15SU9bGoTTcfrSGBfcFBDUTwnp_BX-FiMrI4IxmfPkXIKhzOEHMQiKzDJGVQrsh4SkHKNkyANpGTl8D7cGUiF24Bm1X6Csp_5t1bsE2K2Ktv7nbSBKVmbMaiteMTZRf9oeV_QpL4wB7C8pXA3D92Zd63sUkHLL_iXc4pYXC8sJKBW3_7PTHzNDXCcEOqji7DNeqEiDAaUB0jb9sHf_QH1xyvdq1Op7b5hCWC3S7BRHc3Z7iF5cMg-xEByX3Zz3A7nBIQqn7xvQWQSPtC92ChzMgoShvUHe5qusN-t2ZdX2sig0G73IbyOmNe83wAgy8',
          disable: false,
          marketplaces: [
            {
              id: 'A1AM78C64UM0Y8',
              name: 'Amazon.com.mx',
              countryCode: 'MX',
              defaultCurrencyCode: 'MXN',
              defaultLanguageCode: 'es_MX',
              domainName: 'www.amazon.com.mx'
            },
            {
              id: 'A1MQXOICRS2Z7M',
              name: 'SI CA Prod Marketplace',
              countryCode: 'CA',
              defaultCurrencyCode: 'CAD',
              defaultLanguageCode: 'en_CA',
              domainName: 'siprod.stores.amazon.ca'
            },
            {
              id: 'A2EUQ1WTGCTBG2',
              name: 'Amazon.ca',
              countryCode: 'CA',
              defaultCurrencyCode: 'CAD',
              defaultLanguageCode: 'en_CA',
              domainName: 'www.amazon.ca'
            },
            {
              id: 'A2ZV50J4W1RKNI',
              name: 'Non-Amazon',
              countryCode: 'US',
              defaultCurrencyCode: 'USD',
              defaultLanguageCode: 'en_US',
              domainName: 'sim1.stores.amazon.com'
            },
            {
              id: 'A3H6HPSLHAK3XG',
              name: 'Non-Amazon',
              countryCode: 'MX',
              defaultCurrencyCode: 'MXN',
              defaultLanguageCode: 'es_MX',
              domainName: 'sidevo.stores.amazon.mx'
            },
            {
              id: 'AHRY1CZE9ZY4H',
              name: 'Amazon.com Invoicing Shadow Marketplace',
              countryCode: 'US',
              defaultCurrencyCode: 'USD',
              defaultLanguageCode: 'en_US',
              domainName: 'invoicing-shadow-marketplace.amazon.com'
            },
            {
              id: 'ATVPDKIKX0DER',
              name: 'Amazon.com',
              countryCode: 'US',
              defaultCurrencyCode: 'USD',
              defaultLanguageCode: 'en_US',
              domainName: 'www.amazon.com'
            }
          ],
          cdate: '2021-09-01 10:42:17'
        }
      ],

      rules: {
        sellingPartnerId: [
          { required: true, message: '请填写店铺ID', trigger: 'blur' }
        ],
        shopName: [
          { required: true, message: '请填写店铺名称', trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    // this.fn()
    this.init()
  },
  methods: {
    async init() {
      this.$store.dispatch('app/toggleDialog', true)
      const data = await sotreList()
      if (Array.isArray(data)) {
        this.pickupInfo = data
      }

      this.$store.dispatch('app/toggleDialog', false)
    },
    addInfo() {
      this.editType = 'add'
      this.dialogFormVisible = true
    },
    editInfo(index) {
      this.editType = 'edit'
      this.dialogFormVisible = true
      // 表达回显重置前提条件
      this.$nextTick(function() {
        this.form = clone(this.pickupInfo[index])
      })
    },
    toCheck() {
      window.open(
        'https://sellercentral.amazon.com/apps/authorize/consent?application_id=amzn1.sellerapps.app.07f37775-d00a-4351-ac87-8f1ed2aab66d'
      )
    },
    // 同步信息
    async synchronize(item) {
      this.$store.dispatch('app/toggleDialog', true)
      const data = await manualSync({
        id: item.id
      })
      this.$store.dispatch('app/toggleDialog', false)
      if (data.code === 200) {
        this.$message.success('同步成功！')
      } else {
        this.$message.error(data.message || '同步失败！')
      }
    },
    async saveInfo() {
      this.$store.dispatch('app/toggleDialog', true)
      const data = await saveOrUpdate(this.form)
      if (data.code === 200) {
        this.$message({
          message: '保存成功',
          type: 'success'
        })
        this.init()
        this.dialogFormVisible = false

        setTimeout(() => {
          this.$refs['ruleForm'].resetFields()
          this.form = {
            sellingPartnerId: '',
            shopName: ''
          }
        }, 1000)
      } else {
        this.$message.error(data.message || '保存失败！')
      }
      this.$store.dispatch('app/toggleDialog', false)
    },

    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
          this.resetForm('ruleForm')
        })
        .catch(_ => {})
    },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.saveInfo()
        } else {
          return false
        }
      })
    },
    resetForm(formName) {
      if (this.$refs[formName]) this.$refs[formName].resetFields()
      this.form = {
        sellingPartnerId: '',
        shopName: ''
      }
    }
  }
}
</script>

<style scoped>
.EndWaybillList >>> .el-textarea__inner {
  min-height: 60px !important;
}
</style>

<style lang="scss" scoped>
.item {
  position: absolute;
  right: -25px;
  top: 3px;
  font-size: 20px;
}
.add-btn-box {
  right: 0;
  top: -6px;
}
</style>
